<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-12-02
 * Time: 16:50
 */

namespace app\app\controller;


use app\constant\ActivesConst;
use app\constant\KanJiaConst;
use app\constant\OrderConst;
use app\helper\KanJiaHelper;
use app\model\AdminActives;
use app\model\AdminActiveSku;
use app\model\AdminKanjiaHelp;
use app\model\AdminKanjiaOrder;
use app\model\AdminKanjiaRule;
use app\util\ReturnCode;
use Exception;
use think\Db;
use think\exception\DbException;

class KanJia extends Base
{
    public function createOrder()
    {
        $goods_id = $this->request->param('goods_id');
        $sku_id = $this->request->param('sku_id');
        $where = ['goods_id' => $goods_id, 'uid' => $this->userInfo['uid'], 'sku_id' => $sku_id];
        $where = $this->addTid($where);
        //先判断当前用户是否参加
        $kanjiaModel = AdminKanjiaOrder::get($where);
        if ($kanjiaModel) {
            //说明已经参加过了
            return $this->buildSuccess($kanjiaModel->getData());
        } else {
            $goodsModel = AdminActives::get($goods_id, null, true);
            if (!$goodsModel || $goodsModel->type !== ActivesConst::ACTIVE_TYPE_KJ) {
                return $this->buildFailed(ReturnCode::FAILED, '活动不存在');
            } else {
                if ($goodsModel->status !== ActivesConst::STATUS_NORMAL) {
                    return $this->buildFailed(ReturnCode::FAILED, '活动已结束');
                }
            }

            $skuModel = AdminActiveSku::get($sku_id, null, true);
            if (!$skuModel || $skuModel->del == 1) {
                return $this->buildFailed(ReturnCode::FAILED, '活动不存在');
            } else {
                if ($skuModel->stock <= 0) {
                    return $this->buildFailed(ReturnCode::FAILED, '来晚了，商品卖完咯');
                }
            }
            $ruleModel = AdminKanjiaRule::get(['tid' => $this->getUserTid(), 'sku_id' => $sku_id]);
            if ($ruleModel) {
                $where['rule_id'] = $ruleModel->id;
            }
            $where['sid'] = $goodsModel->sid;
            $where['original_price'] = $skuModel->original_price;
            $where['current_price'] = $skuModel->original_price;
            $where['lowest_price'] = $skuModel->lowest_price;
            try {
                Db::startTrans();
                $done = AdminKanjiaOrder::create($where);
                $kanJiaResult = (new KanJiaHelper())->kanJia($done->id,$this->userInfo['uid']);
                if ($done && $kanJiaResult['done']) {
                    Db::commit();
                    return $this->buildSuccess($done->id);
                } else {
                    throw new Exception();
                }
            } catch (Exception $e) {
                Db::rollback();
            }
            return $this->buildFailed(ReturnCode::FAILED, '操作失败');
        }
    }
    public function get(){
        $kanJiaOrderId = $this->request->param('kanjia_order_id');
        $model = AdminKanjiaOrder::get($kanJiaOrderId);
        if($model){
            $orderData = $model->getData();
            if($model->order_item_id!=null){
                $model->order;
                $model->orderItem;
                //这里要判断，如果关联的订单不处于正常状态，就取消关联（即前台并不会收到关联的订单信息）
                if($model->order['trade_status']==OrderConst::ORDER_STATUS_NORMAL||$model->order['trade_status']==OrderConst::ORDER_STATUS_USED){
                    $orderData['order']=$model->order;
                    $orderData['order_item']=$model->orderItem;
                }else{
                    $orderData['order_id']=null;
                    $orderData['order_item_id']=null;
                }
                $orderData['goods_img']=$model->orderItem['goods_img'];
                $orderData['goods_title']=$model->orderItem['goods_title'];
            }else{
                $model->goods;
                $orderData['goods_img'] = json_decode($model->goods['banners'])[0];
                $orderData['goods_title'] = $model->goods['title'];
            }
            return $this->buildSuccess($orderData);
        }
        return $this->buildFailed(ReturnCode::FAILED,'无此订单');
    }
    public function close(){
        $kanJiaOrderId = $this->request->param('kanjia_order_id');
        $model = AdminKanjiaOrder::get(['tid'=>$this->getUserTid(),'id'=>$kanJiaOrderId,'uid'=>$this->userInfo['uid']]);
        if($model){
            $model->setAttr('order_id',null);
            $model->setAttr('order_item_id',null);
            $done = $model->allowField(true)->save();
            if($done){
                return $this->buildSuccess(null);
            }
            return $this->buildFailed(ReturnCode::FAILED,'操作失败');
        }
        return $this->buildFailed(ReturnCode::FAILED,'无此订单');
    }
    public function kanJia(){
        $id = $this->request->param('kanjia_order_id');
        $kanJiaResult = (new KanJiaHelper())->kanJia($id,$this->userInfo['uid']);
        if ($kanJiaResult['done']) {
            return $this->buildSuccess($kanJiaResult['randPrice']);
        }
        return $this->buildFailed(ReturnCode::FAILED, '操作失败');
    }
    public function getOrderList()
    {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $type = $this->request->get('type', '', 'intval');
        //这个接口只查询抢购的订单
        $where = [];
        $where = $this->addTid($where);
        $where['uid'] = $this->userInfo['uid'];
        $obj = new AdminKanjiaOrder();
        //订单类型 0 全部 1进行中 2砍价完成待支付 3已关闭

        switch ($type) {
            case 1:
                $where['status'] = KanJiaConst::STATUS_NORMAL;
                $where['is_lowest'] = KanJiaConst::IS_LOWEST_NO;
                break;
            case 2:
                $where['status'] = KanJiaConst::STATUS_NORMAL;
                $where['is_lowest'] = KanJiaConst::IS_LOWEST_YES;
                break;
            case 3:
                $where['status'] = KanJiaConst::STATUS_CLOASE;
                break;
        }
        try {
            $listObj = $obj->where($where)->order('create_time DESC')->paginate($limit, false, ['page' => $start])->each(function ($value, $key) {
                if($value->order_item_id!=null){
                    $value->orderItem;
                    $value['goods_img'] = $value->orderItem['goods_img'];
                    $value['goods_title'] = $value->orderItem['goods_title'];
                }else{
                    $value->goods;
                    $value['goods_img'] = json_decode($value->goods['banners'])[0];
                    $value['goods_title'] = $value->goods['title'];
                }

            })->toArray();
            return $this->buildSuccess([
                'list' => $listObj['data'],
                'count' => $listObj['total']
            ]);
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED, '获取失败');

    }

    /**
     * 获取助力人员列表
     */
    public function getHelp(){
        $kanJiaId = $this->request->param('kanjia_order_id');
        if(!isset($kanJiaId)){
            return $this->buildFailed(ReturnCode::INVALID,'无效的参数');
        }
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $obj = new AdminKanjiaHelp();
        $where = ['kanjia_order_id'=>$kanJiaId];
        $where = $this->addTid($where);
        try {
            $listObj = $obj->where($where)->order('create_time ASC')->paginate($limit, false, ['page' => $start])->toArray();
            return $this->buildSuccess([
                'list' => $listObj['data'],
                'count' => $listObj['total']
            ]);
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED,'获取失败');

    }


}